import React, { useState, useEffect } from 'react'
import { View, Image, Text } from '@tarojs/components'
import MD5 from 'MD5'
import { AtInput, AtButton, AtCountdown } from 'taro-ui'
import ToLogin from '../../compontents/toLogin'
import Taro from '@tarojs/taro'
import lhTool from 'lh-tool'


import useModel from 'flooks';
import store from '../../stores/index'

import api from '../../http/api'
const { ajaxOrderInfo,ajaxPay,ajaxUpdateOrderStatus } = api

import './index.less'
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/countdown.scss";


export default (props: any) => {
  useEffect(() => {
    getOrderInfo()
  }, [])
  // 备注
  const [remark, setRemark] = useState('')
  // 用户信息
  const info: any = Taro.getStorageSync('info')
  const { loginId, nickName, tel, uSchoolId } = JSON.parse(info).userInfo
  // 订单号
  const orderNum = props.tid.split('orderNum=')[1].split('&')[0]
  const [orderInfo, setOrderInfo]: any = useState({})
  const [seconds,setSeconds] = useState(0)
  // 备注
  const remarkChange = (e) => {
    console.log(e)
  }
  const makeCode= n => {
		var num = "";
		for (var i = 0; i < n; i++) {
			num += Math.floor(Math.random() * 10)
		}
		return num +'';
	}
  // 点击支付
  const payNow = () => {
    const params:any = {
      appId:'wx069bb9fd47eb702b',
      timeStamp:parseInt(new Date().getTime()/1000+'')+'',
      nonceStr: makeCode(30),
      package: orderInfo.prepay_id,
      signType: 'MD5',    //RSA
    }
    const str = `appId=${params.appId}&nonceStr=${params.nonceStr}&package=${params.package}&signType=${params.signType}&timeStamp=${params.timeStamp}&key=liuhu666liuhu666liuhu666liuhu666`
    const paySign = MD5(str) 
    params.paySign = paySign
    Taro.requestPayment({
      ...params,
      success: function (res) {
        ajaxPay({
          remark:'',
          uOrderId:orderInfo.id,
          businessManageId:orderInfo.businessManageId,
          id:orderInfo.ticketDetail.id,
          num:orderInfo.ticketDetail.num
        }).then(_=>{
          Taro.redirectTo({
            url:`/pages/uOrder/index`
          })
        })

      },
      fail: function (res) {
        Taro.showToast({
          title:'支付失败',
          icon:'none'
        })
      }
    })
  }
  // 倒计时结束
  const onTimeUp = () => {
    setSeconds(0)
    ajaxUpdateOrderStatus({
      uOrderId:orderInfo.id
    })
  }
  // 获取订单详情
  const getOrderInfo = () => {
    ajaxOrderInfo({ orderNum }).then((res: any) => {
      setOrderInfo(res.data)
      const {time,endTime} = res.data
      const sec = new Date(endTime).getTime()/1000-new Date().getTime()/1000
      setSeconds(sec<0?0:sec)
    })
  }
  return (
    <View className='uPay'>
      <ToLogin url='/pages/active/index'></ToLogin>

      {
        orderInfo.ticketDetail && <View className=''>
          <View className='time'>
            {
              seconds>0?<View>
                <View className='t1'>支付剩余时间</View>
                <View className='t2'>
                  <AtCountdown
                  format={{ hours: ':', minutes: ':', seconds: '' }}
                  seconds={seconds}
                  onTimeUp={onTimeUp}
                  isShowHour={false}
                />
                </View>
              </View>:<View className='dis'>订单已过期，请重新下单</View>
            }
            
          </View>
          <View className='name'>
            <Text className='n1'>{nickName}</Text>
            <Text className='n2'>{tel}</Text>
          </View>
          <View className='orderInfo'>
            <View className='info1'>
              <Image className='img' src={orderInfo.ticketDetail.src.split(',')[0]} />
              <View className='info1Right'>
                <View className='info1Title'>{orderInfo.ticketDetail.title}</View>
                <View className='num'>
                  <View className='num1'>¥{orderInfo.ticketDetail.price}</View>
                  <View className='num2'>x{orderInfo.ticketNum}</View>
                </View>
              </View>
            </View>
            <View className='info2'>
              <View className='txt1'>订单编号：{orderInfo.orderNum}</View>
              <View className='txt2'>下单时间：{lhTool.formatDate.format(new Date(orderInfo.time), 'yyyy/MM/dd hh:mm:ss')}</View>
            </View>
            <View className='info3'>
              <AtInput
                name=''
                title='订单备注：'
                type='text'
                placeholder='请输入订单备注'
                value={remark}
                onChange={remarkChange}
                disabled={seconds>0?false:true}
              />
            </View>
          </View>
          <View className='goodsInfo'>
            <View className='good1'>
              <View className='txt'>商品总额</View>
              <View className='txt'>¥{orderInfo.price}</View>
            </View>
            <View className='good2'>
              <Text className='txt1'>共1件商品，实付：</Text>
              <Text className='txt2'>¥{orderInfo.price}</Text>
            </View>
            <View className='foot'>
              <AtButton disabled={seconds>0?false:true} onClick={payNow} className='btn' size='small'>立即支付</AtButton>
            </View>
          </View>

        </View>
      }
    </View>
  );
};
